<?php
/**
 * Function:
 * Description:
 * Abo 2018/10/16 09:20
 * Email: abo2013@foxmail.com
 */

namespace app\index\controller;


use think\Controller;
use app\common\lib\Redis;
use app\common\lib\Util;
use app\common\lib\redis\Predis;

class Login extends Controller
{
    public function hello($name = 'ThinkPHP5')
    {
        return 'hello,' . $name;
    }

    public function helloH($name = 'ThinkPHP5')
    {
        return 'hello,' . $name;
    }

    public function smslogin()
    {

        $phoneNum = intval($_POST['phone_num']);
        $smsCode = intval($_POST['code']);
        info( "进入:{$smsCode}" );
        try {

            $redis = new \Swoole\Coroutine\Redis();
            $redis->connect('127.0.0.1', '6379');
            $redisCode = $redis->get($phoneNum);

            info( "{$smsCode}||{$redisCode}" );

            if ($redisCode == $smsCode) {
                // 写入redis
                $data = [
                    'user' => $phoneNum,
                    'srcKey' => md5( 'user_' . $phoneNum ),
                    'time' => time(),
                    'isLogin' => true,
                ];
                $redis->set( 'user_' . $phoneNum, json_encode( $data ) );

                return Util::show(true, 'ok', $data);
            } else {
                return Util::show(false, 'login error');
            }
        } catch (\Exception $e) {
            return Util::show(false, $e->getMessage() );
        }
    }

    /**
     * http://127.0.0.1:8811/index.php?s=index/login/smscode&phone_num=13016071804
     * @return string
     */
    public function smsCode()
    {
        $phoneNum = intval( $_GET[ 'phone_num' ] );

        $Util = new Util();
        $smsCode = $Util->randomNumber( 6 );

        // http task 目录执行
        $taskData = [
            'data' => [
                'phone' => $phoneNum,
                'code' => $smsCode
            ],
            'method' => 'getSmsCode',
        ];
        $_POST[ 'http_server' ] ->task( $taskData );
/*
 *使用 swoole task 任务执行
        info( '使用 swoole task 任务执行: 发送短信' . $data[ 'phone' ] . '~' . $data[ 'code' ] );
*/
        $redis = new \Swoole\Coroutine\Redis();
        $redis->connect( config( 'redis.host' ), config( 'redis.port' ) );
        $redis->set( $phoneNum, $smsCode, config( 'redis.out_time' ) );

        return Util::show( true, '发送成功', $smsCode );
    }
}